package com.csun.nusing.ui.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.csun.nusing.R;
import com.csun.nusing.bean.UrlBean;
import com.csun.nusing.bean.jsonbean.BaseJsonBean;
import com.csun.nusing.presenter.CommonPresenter;
import com.csun.nusing.presenter.inter.IBase;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.util.SPUtils;
import com.csun.nusing.util.ToastUtil;
import com.csun.ttfutil.TTFSdk;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.home.administrator.okhttplibrary.IOkTaskCallback;
import com.home.administrator.okhttplibrary.OkHttpTask;
import com.home.administrator.okhttplibrary.OkHttpTask.OkHttpTaskBuidler.OkType;
import com.linktop.whealthService.HealthApi;
import com.linktop.whealthService.HealthApi.BleCallBack;
import com.linktop.whealthService.HealthApi.EcgCallBack;
import com.linktop.whealthService.HealthApi.HealthApiCallBack;
import com.linktop.whealthService.OnBLEService;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 血压测试的主界面 ClassName: BloodPressTestActivity
 * 
 * @Description: TODO
 * @author fzq
 * @date 2017-10-25
 */
public class ECGMainActivity extends BaseActivity<CommonPresenter> implements
		IBase {

	public static final String TAG = "fzq";
	private LineChart mChart;
	private TextView brmaxtv;
	private TextView brmintv;
	private TextView moodtv;// 心情
	private TextView changetv;// 心率变异
	private TextView testtv;// 测试按钮
	private TextView historydatetv;// 历史数据
	private HealthApi mHealthApi;

	private final boolean START = true;
	private final boolean STOP = false;
	private boolean ecg_button_state = true;
	private Timer batteryQueryTimer;
	public boolean ecg_modual_exist = true;
	public int ecgDate;
	public long currentTime;
	private StringBuilder stringBuilder;
	private String olderId;
	private String authorization;
	protected int RRMAX;
	protected int RRMIN;
	protected int Mood;
	protected int hrv;
	private RelativeLayout navrl;
	private boolean isFamily;

	@Override
	public int getContentViewId() {
		return R.layout.activity_ecgmain;
	}

	@Override
	public void initSubViews(View view) {
		super.initSubViews(view);
		/**
		 * find控件
		 */
		initView();
		initHealth();
		initLine();
	}

	@Override
	public void initData() {
		super.initData();
		initDate();
	}

	/**
	 * 初始化心电图
	 * 
	 * @Description: 初始化心电图
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-16
	 */
	private void initLine() {
		mChart.setDrawGridBackground(false);
		// set the description text
		mChart.setDescription("");
		mChart.setNoDataTextDescription("");
		// enable touch gestures
		mChart.setTouchEnabled(true);
		// enable scaling and dragging
		mChart.setDragEnabled(true);
		mChart.setScaleXEnabled(true);
		mChart.setScaleYEnabled(false);
		mChart.setDescriptionColor(Color.TRANSPARENT);
		mChart.setHighlightPerDragEnabled(false);
		mChart.setHighlightPerTapEnabled(false);
		mChart.setVisibleXRangeMaximum(100);
		mChart.setVisibleXRangeMinimum(100);
		LineData data = new LineData();
		data.setValueTextColor(Color.TRANSPARENT);
		// add empty data
		mChart.setData(data);

		// mChart.setPinchZoom(true);
		XAxis xAxis = mChart.getXAxis();
		xAxis.setEnabled(true);
		xAxis.setTextColor(Color.TRANSPARENT);// 横坐标颜色
		xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);// 把坐标轴放在上下 参数有：
		YAxis leftAxis = mChart.getAxisLeft();
		leftAxis.removeAllLimitLines(); // reset all limit lines to avoid
										// overlapping lines
		leftAxis.setAxisMinValue(-5000f);
		leftAxis.setTextColor(Color.TRANSPARENT);// 纵坐标颜色
		leftAxis.setAxisMaxValue(5000f);
		leftAxis.setLabelCount(100, false);
		leftAxis.setStartAtZero(false);
		mChart.getAxisRight().setEnabled(false);
		Legend l = mChart.getLegend();
		l.setForm(Legend.LegendForm.LINE);
	}

	/**
	 * 初始化折线图
	 * 
	 * @Description: TODO
	 * @param @return
	 * @return LineDataSet
	 * @throws
	 * @author fzq
	 * @date 2017-10-31
	 */
	private LineDataSet createDateSet() {
		LineDataSet set = new LineDataSet(null, null);
		set.setAxisDependency(YAxis.AxisDependency.LEFT);
		set.setColor(Color.WHITE);
		set.setCircleColor(Color.TRANSPARENT);
		set.setLineWidth(2f);
		set.setCircleSize(0f);
		set.setFillAlpha(65);
		set.setFillColor(ColorTemplate.getHoloBlue());
		set.setHighLightColor(Color.TRANSPARENT);
		set.setValueTextColor(Color.TRANSPARENT);
		set.setValueTextSize(9f);
		set.setDrawValues(false);
		return set;
	}

	/**
	 * 折线图添加数据
	 * 
	 * @Description: TODO
	 * @param @param yvalue
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-31
	 */
	private void addDateEntry(float yvalue) {

		LineData data = mChart.getData();
		if (data != null) {
			ILineDataSet set = data.getDataSetByIndex(0);
			if (set == null) {
				set = createDateSet();
				data.addDataSet(set);
			}
			// add a new x-value first
			data.addXValue(data.getXValCount() + "");
			data.addEntry(new Entry(yvalue, set.getEntryCount()), 0);

			// let the chart know it's data has changed
			mChart.notifyDataSetChanged();

			// limit the number of visible entries
			mChart.setVisibleXRangeMaximum(100);
			mChart.setVisibleXRangeMinimum(100);
			// move to the latest entry
			mChart.moveViewToX(data.getXValCount() - 100);

		}
	}

	/**
	 * 操作控件
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-13
	 */
	private void initView() {
		mChart = findViewById(R.id.ecg_main_line_chart);
		brmaxtv = findViewById(R.id.ecg_main_br_max_tv);
		brmintv = findViewById(R.id.ecg_main_br_min_tv);
		moodtv = findViewById(R.id.ecg_main_mood_tv);
		changetv = findViewById(R.id.ecg_main_change_tv);
		testtv = findViewById(R.id.ecg_main_messure_test_tv);
		historydatetv = findViewById(R.id.ecg_main_historydata_tv);

		testtv.setOnClickListener(new click());
		historydatetv.setOnClickListener(new click());
	}

	/**
	 * 獲取數據,展示數據 图表展示
	 * 
	 * @Description:
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	private void initDate() {
		olderId = getIntent().getStringExtra("olderId");
		stringBuilder = new StringBuilder();
		authorization = (String) SPUtils.get(this, "authorization", "");
		navrl = findViewById(R.id.nav_rl);
		isFamily = getIntent().getBooleanExtra("isFamily", false);
		if (isFamily) {
			navrl.setBackgroundResource(R.drawable.main_whiteyello_color_shape);
		}
	}

	/**
	 * @Description: 初始化测量
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	private void initHealth() {
		mHealthApi = new HealthApi();
		mHealthApi.init(getApplicationContext(), new healthapicallback(),
				mbpHandler, mbtHandler, moxHandler, mbsHandler,
				new ecgcallback());

		mHealthApi.setBleCallBack(new blecallback());

		Log.e("version", HealthApi.getVersion());
	}

	public void showHistory() {
		Intent intent = new Intent(this, ECGHistoryActivity.class);
		intent.putExtra("olderId", olderId);
		intent.putExtra("isFamily", isFamily);
		startActivity(intent);
	}

	/**
	 * 处理所有点击事件 ClassName: click
	 * 
	 * @Description: TODO
	 * @author fzq
	 * @date 2017-10-13
	 */
	private class click implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.ecg_main_messure_test_tv:
				startMessure();// 测量
				break;
			case R.id.ecg_main_historydata_tv:
				showHistory();
				break;
			default:
				break;
			}
		}
	}

	/**
	 * post 上传数据
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-31
	 */
	public void sendData() {
		Map<String, String> param = new HashMap<String, String>();
		param.put("ECG", "" + stringBuilder.toString());
		param.put("RRMIN", "" + RRMIN);
		param.put("RRMAX", "" + RRMAX);
		param.put("mood", "" + Mood);
		param.put("hrv", "" + hrv);
		param.put("timebase", "10");
		param.put("gain", "10");
		param.put("oldmanId", olderId);
		Log.e("fzq", "-------**********");

		OkHttpTask.newInstance(this).post(param, OkType.form)
				.addHeader("authorization", authorization)
				.enqueue(new IOkTaskCallback() {
					@Override
					public void onSuccess(String result) {
						if (result != null) {
							Log.e("fzq", "-------" + result);
							Gson gson = new Gson();
							BaseJsonBean baseJsonBean = gson.fromJson(result,
									BaseJsonBean.class);
							ToastUtil.showMessage(getApplicationContext(),
									baseJsonBean.getMessage());
						}
					}
				}).start(UrlBean.FOLLOWECGUPURL);
	}

	/**
	 * 测量心率
	 * 
	 * @Description: 测量心率
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	protected void startMessure() {
		if (ecg_modual_exist) {
			if (ecg_button_state == START) {
				if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
					mHealthApi.ecgStart();
					ecg_button_state = STOP;
					testtv.setText(R.string.stop);
					// 模拟
					mChart.getData().clearValues();
					stringBuilder = new StringBuilder();
					mChart.notifyDataSetChanged();
					moodtv.setText(R.string.ecg_mood_s);
					changetv.setText(R.string.ecg_change_s);
					brmintv.setText(R.string.ecg_rr_min_s);
					brmaxtv.setText(R.string.ecg_rr_max_s);
					initLine();
				} else {
					BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
					if (bta == null) {
						Toast.makeText(this, R.string.not_support_ble, Toast.LENGTH_SHORT)
								.show();
					} else {
						if (!bta.isEnabled()) {
							startActivityForResult(
									new Intent(
											"android.bluetooth.adapter.action.REQUEST_ENABLE"),
									2);
						}
					}
				}
			} else {
				mHealthApi.ecgStop();
				ecg_button_state = START;
				testtv.setText(R.string.measure);
			}
		} else {
			Toast.makeText(ECGMainActivity.this,R.string.please_re_relative, Toast.LENGTH_SHORT)
					.show();
		}
	}

	private class healthapicallback implements HealthApiCallBack {

		@Override
		public void healthCallBack(int type, Object data) {
			// TODO Auto-generated method stub
			switch (type) {
			case HealthApi.BIND_FINISHED:
				break;
			case HealthApi.BATTERY:
				break;
			case HealthApi.UPDATA_CON_INTERVAL_FAIL_ACTION:
				break;
			case HealthApi.QUERY_ECG_MODULE_EXIST:
				byte modual = (Byte) data;
				Log.e("fzq", "-----modual  " + modual);
				ecg_modual_exist = true;
				// if (modual == 0)
				// ecg_modual_exist = false;
				// else if (modual == 1) {
				// ecg_modual_exist = true;
				// }
				break;
			case HealthApi.QUERY_BS_MODULE_EXIST:
				byte modual1 = (Byte) data;
				break;
			case HealthApi.INTENT_DEVICE_VERSION_SOFE:
				String sofe = (String) data;
				break;
			case HealthApi.INTENT_DEVICE_VERSION_HARD:
				String hard = (String) data;
				break;
			}
		}
	}

	/**
	 * 蓝牙返回数据 ClassName: blecallback
	 * 
	 * @Description: TODO
	 * @author fzq
	 * @date 2017-10-27
	 */
	private class blecallback implements BleCallBack {
		@Override
		public void bleCallBack(int type, Object data) {
			if (type == HealthApi.BLE_STATUS) {
				setBleUiState((Integer) data);
			}
		}
	}

	private void modual_init() {
		mHealthApi.ecgQuery();
		mHealthApi.bsQuery();
		mHealthApi.batteryQuery();

		if (batteryQueryTimer == null)
			batteryQueryTimer = new Timer();
		batteryQueryTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				mHealthApi.batteryQuery();
			}
		}, 300000, 300000);
	}

	private void setBleUiState(int mState) {

		switch (mState) {
		case OnBLEService.BLE_CONNECTED:
			break;
		case OnBLEService.BLE_DISCONNECTED:
			break;
		case OnBLEService.BLE_NOTIFICATION_ENABLED:
			modual_init();
			break;
		case OnBLEService.BLE_NOTIFICATION_NOTENABLED:
			break;
		default:
			break;
		}

	}

	private class ecgcallback implements EcgCallBack {

		@Override
		public void onReceive(int[] data) {
			// TODO Auto-generated method stub
			switch (data[0]) {
			case HealthApi.ECG_DATA:
				// tv.append("SmoothedRaw: " + data + "\n");
				Log.e(TAG, "---------ecg value = " + data[1]);
				ecgDate = data[1];
				if (ecgDate > 5000) {
					ecgDate = 5000;
				} else if (ecgDate < -5000) {
					ecgDate = -5000;
				}
				//
				if (System.currentTimeMillis() - currentTime > 10) {
					addDateEntry(ecgDate);
					stringBuilder.append(ecgDate + ",");
					currentTime = System.currentTimeMillis();
				}
				break;
			case HealthApi.ECG_HEARTRATE:
				final int avg_hr = data[1];
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						Log.e(TAG, "---------HR" + avg_hr);// 心率
					}
				});
				break;
			case HealthApi.ECG_RRMAX:
				final int rrmaxint = data[1];
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						Log.e(TAG, "---------RRMAX" + rrmaxint);
						brmaxtv.setText(rrmaxint + getString(R.string.ecg_rr_max));
						RRMAX = rrmaxint;
					}
				});
				break;
			case HealthApi.ECG_RRMIN:
				final int rrminint = data[1];
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						Log.e(TAG, "---------RRMin" + rrminint);
						brmintv.setText(rrminint + getString(R.string.ecg_rr_min));
						RRMIN = rrminint;
					}
				});
				break;
			case HealthApi.ECG_HRV:
				final int hRV = data[1];
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Log.e(TAG, "---------hRV" + hRV);
						changetv.setText(hRV + getString(R.string.ecg_change));
						hrv = hRV;
					}
				});
				break;
			case HealthApi.ECG_MOOD:
				final int mood = data[1];
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Log.e(TAG, "---------mood" + mood);
						moodtv.setText(mood + getString(R.string.ecg_mood));
						Mood = mood;
					}
				});
				break;
			case HealthApi.ECG_BR:
				// tv.append("Robust HR: " + data + "\n");
				Log.e("Robust HR ", data + "\n" + "");
				final int br = data[1];
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Log.e(TAG,
								"---------br" + br + "time --- "
										+ System.currentTimeMillis());

					}
				});
				break;
			case HealthApi.ECG_END:
				testHander.sendEmptyMessage(0x12345);
				break;
			default:
				break;
			}
		}
	}

	private Handler testHander = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if (msg.what == 0x12345) {
				testtv.setText(R.string.measure);
				TTFSdk.speak(mSpeechSynthesizer,"心电测量结束");
//				mySyntherizer.speak("心电测量结束");
				ecg_button_state = START;
				sendData();
			}
		}
	};

	/**
	 * 温度测量
	 */
	private Handler mbtHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
		}
	};

	/**
	 * 血氧测试
	 */
	@SuppressLint("HandlerLeak")
	private Handler moxHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler mbpHandler = new Handler() {
		public void handleMessage(Message msg) {
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler mbsHandler = new Handler() {
		public void handleMessage(Message msg) {
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mHealthApi != null)
			if (batteryQueryTimer != null)
				batteryQueryTimer.cancel();
		batteryQueryTimer = null;
	}

	/**
	 * 对back键的点击做判断，如果按back键，默认退回到主页面
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent();
			intent.putExtra("bleOn", true);
			setResult(0x22, intent);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// 监听返回键
	public void OnBACK(View view) {
		Intent intent = new Intent();
		intent.putExtra("bleOn", true);
		setResult(0x22, intent);
		finish();
	}

}
